#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>

#define n 10

using namespace std;

bool c[n][n] =

    /*
    {
    {0,0,1,1},
    {0,0,1,1},
    {1,1,0,0},
    {1,1,0,0}};
    */

    {
        {0, 1, 0, 0, 1, 1, 0, 0, 0, 0},
        {1, 0, 1, 0, 0, 0, 1, 0, 0, 0},
        {0, 1, 0, 1, 0, 0, 0, 1, 0, 0},
        {0, 0, 1, 0, 1, 0, 0, 0, 1, 0},
        {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 1, 1, 0},
        {0, 1, 0, 0, 0, 0, 0, 0, 1, 1},
        {0, 0, 1, 0, 0, 1, 0, 0, 0, 1},
        {0, 0, 0, 1, 0, 1, 1, 0, 0, 0},
        {0, 0, 0, 0, 1, 0, 1, 1, 0, 0}};

/*
{
    {0, 0, 0, 1, 1, 1, 0, 0, 0},
    {0, 0, 0, 1, 1, 1, 0, 0, 0},
    {0, 0, 0, 1, 1, 1, 0, 0, 0},
    {1, 1, 1, 0, 0, 0, 1, 1, 1},
    {1, 1, 1, 0, 0, 0, 1, 1, 1},
    {1, 1, 1, 0, 0, 0, 1, 1, 1},
    {0, 0, 0, 1, 1, 1, 0, 1, 1},
    {0, 0, 0, 1, 1, 1, 1, 0, 1},
    {0, 0, 0, 1, 1, 1, 1, 1, 0},
};
*/

bool hamiltion(int x[])
{
    int k = 0;

    bool *s = new bool[n];

    memset(x, -1, n * sizeof(int));
    memset(s, false, sizeof(bool) * n);

    x[0] = 0;
    s[x[0]] = true;
    k = k + 1;

    while (k > 0)
    {
        printf("路径中的第%d个顶点为%d\n", k, x[k - 1] + 1);
        x[k] = x[k] + 1;

        while (x[k] < n)
        {
            if (s[x[k]] == false && c[x[k - 1]][x[k]])
            {
                break;
            }
            else
            {
                x[k] = x[k] + 1;
            }
        }

        if (x[k] < n && (k != n - 1))
        {
            s[x[k]] = true;
            k = k + 1;
            continue;
        }
        else if (x[k] < n && (k == n - 1) && c[x[k]][x[0]])
        {
            break;
        }
        else // this branch is the error solutions which need back_trace
        {
            x[k] = -1;
            k = k - 1;
            s[x[k]] = false;
        }
    }

    delete s;

    if (k == n - 1)
    {
        return true;
    }

    else
    {
        return false;
    }
}

int main(void)
{
    int x[n];

    if (hamiltion(x))
    {
        cout << "存在哈密顿回路 " << endl;

        for (int i = 0; i < n; i++)
        {
            cout << x[i] << "  ";
        }
        cout << endl;
    }
    else
    {
        cout << "不存在哈密顿回路 " << endl;
    }
    system("pause");
    return 0;
}